package captcha

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/mojocn/base64Captcha"
	"log"
	"strings"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct {
	rdb *redis.Client
	ctx context.Context
	// Expiration time of captchas.
	expiration time.Duration
}

func NewRedisStore(ctx context.Context, rdb *redis.Client, expiration time.Duration) base64Captcha.Store {
	s := new(RedisStore)
	s.rdb = rdb
	s.ctx = ctx
	s.expiration = expiration
	return s
}

// set a capt
func (r RedisStore) Set(id string, value string) error {
	key := CAPTCHA + id
	err := r.rdb.Set(r.ctx, key, value, r.expiration).Err()
	if err != nil {
		log.Println(err.Error())
	}
	return err
}

// get a capt
func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	val, err := r.rdb.Get(r.ctx, key).Result()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	if clear {
		err = r.rdb.Del(r.ctx, key).Err()
		if err != nil {
			fmt.Println(err)
			return ""
		}
	}
	return val
}

// verify a capt
func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := r.Get(id, clear)
	return strings.ToLower(v) == strings.ToLower(answer)
}
